package com.realgodo.site.service.communication;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.hibernate.DefaultEntityManager;

import com.realgodo.site.entity.application.communication.Comment;
import com.realgodo.site.entity.space.Space;
import com.realgodo.site.service.application.ApplicationManager;

@Service
@Transactional
public class CommentManager extends DefaultEntityManager<Comment, Long> {

	@Autowired
	protected SessionFactory sessionFactory;

	public Page<Comment> findComments(Page<Comment> page, Long applicationId) {
		Criteria c = sessionFactory.getCurrentSession().createCriteria(
				Comment.class);
		c.add(Restrictions.eq("applicationId", applicationId));
		c.addOrder(Order.desc("createDate"));

		return this.entityDao.findByCriteria(page, c);
	}

	public void saveComment(String title, String content, Long applicationId,
			Space space) {
		Comment comment = new Comment();
		comment.setApplicationId(applicationId);
		comment.setSpace(space);
		comment.setTitle(title);
		comment.setContent(ApplicationManager.convert(content));
		this.entityDao.save(comment);
	}
}
